package com.jdone.compus.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESJSUtils {

    /**
     * AES加密 (CBC模式, PKCS5Padding)
     *
     * @param content 明文内容
     * @param keyStr  密钥
     * @param keySIv  IV（偏移量）
     * @return Base64编码的加密结果
     */
    public static String encrypt(String content, String keyStr, String keySIv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keySIv.getBytes(StandardCharsets.UTF_8));

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * AES解密 (CBC模式, PKCS5Padding)
     *
     * @param encryptedData Base64编码的密文
     * @param keyStr        密钥
     * @param ivStr         IV（偏移量）
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedData, String keyStr, String ivStr) {
        byte[] decrypted = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivStr.getBytes(StandardCharsets.UTF_8));

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decoded = Base64.getDecoder().decode(encryptedData);
            decrypted = cipher.doFinal(decoded);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return new String(decrypted, StandardCharsets.UTF_8);
    }


    /**
     * AES解密 (CBC模式, PKCS5Padding)
     *
     * @param encryptedData Base64编码的密文
     * @param keyStr 密钥（可选）
     * @param ivStr IV（可选）
     * @return 解密后的明文
     */


    public static String decrypt1(String encryptedData, String keyStr, String ivStr) {

        byte[] decrypted = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivStr.getBytes(StandardCharsets.UTF_8));

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decoded = Base64.getDecoder().decode(encryptedData);
            decrypted = cipher.doFinal(decoded);
        } catch (Exception e) {
            e.printStackTrace();
            return "原始加密字符串{}，AES解密失败";
        }

        return new String(decrypted, StandardCharsets.UTF_8);
    }
}

